import { Component, ViewChild } from '@angular/core';
import { Platform, AlertController, Keyboard, IonicApp, Nav, ToastController, App } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { LoginPage } from '../pages/login/login';
import { ThemeProvider } from '../providers/theme/theme';
import { HomePage } from '../pages/home/home';
import { BackProvider } from '../providers/back/back';
import { TabsPage } from '../pages/tabs/tabs';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = LoginPage;
  //返回按键是否按下
  backButtonPressed = false;
  //选择主题
  selectedTheme: String;
  // 导航
  @ViewChild(Nav) nav: Nav;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private themeProvider: ThemeProvider,
    public alertCtrl: AlertController,public keyboard: Keyboard,public app: App,public ionicApp: IonicApp,private toastCtrl: ToastController) {
    this.themeProvider.getActiveTheme().subscribe(val => this.selectedTheme = val);
    

  }

  private init(){
    this.platform.ready().then(() => {
      // 设置状态栏
      this.statusBar.styleDefault();
      this.statusBar.styleLightContent();
      // 隐藏启动页
      this.splashScreen.hide();

      //注册返回按钮的处理方法
        /* this.platform.registerBackButtonAction((): any => {
          this.setupBackButtonBehavior();
        }, 101); */
      });
  }

  //返回按钮事件
  private setupBackButtonBehavior () {
    // If on web version (browser)
    // Register browser back button action(s)
    window.onpopstate = (evt) => {
      if (this.keyboard.isOpen()) {
        //按下返回键时，先关闭键盘
        this.keyboard.close();
        return;
      };
      // 关闭弹出层等
      let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();

      if (activePortal) {
        activePortal.dismiss();
        return;
      }
      // 当前是否存在 可pop 页面
      if (this.app.getActiveNav().canGoBack()){
        this.app.getActiveNav().pop();
      }else{
        this.showExit();
      }
    };
    if (window.location.protocol !== "file:") {
      // Fake browser history on each view enter
      this.app.viewDidEnter.subscribe((app) => {
        history.pushState(null, document.title, location.href);
        //history.pushState (null, null, "");
      });
    }
  }
 

  //退出应用方法
  private showExit(): void {
    //如果为true，退出
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
        //第一次按，弹出Toast
        this.toastCtrl.create({
            message: '再按一次退出应用',
            duration: 2000,
            position: 'top'
        }).present();
      //标记为true
      this.backButtonPressed = true;
      //两秒后标记为false，如果退出的话，就不会执行了
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }
}
